import React, {useCallback, useRef} from 'react'
import Taro from '@tarojs/taro'
import {Image, View, Text} from '@tarojs/components'
import Nav from '@/components/Nav/Nav'
import {CommentItem} from '@/packageA/hooks/senne'
import NoResult from '@/components/NoResult/NoResult'
import './Comment.scss'

interface Props {
  show: boolean
  list: CommentItem[]
  authorId?: string
  toggleLike(id: string, index: number): void
  onBack (): void
}

const Comment: React.FC<Props> = (props) => {
  const {show, list, authorId, onBack, toggleLike} = props
  const userInfo = useRef(Taro.getStorageSync('userInfo'))

  const formatTime = useCallback((time: string) => {
    return time.substring(0, time.length - 3)
  }, [])

  return <View className={`comment_wrap ${show ? 'entry' : ''}`}>
    <View className='comment_title_wrap'>
      <Nav color='#000' back={onBack}>
        <Image className='nav_comment_avatar' src={userInfo.current.avatarUrl} />
        <Text className='nav_comment_text'>{userInfo.current.nickname}</Text>
      </Nav>
    </View>
    <View className='comment_list'>
      {
       list.length ? list.map((item, index) => <View className='comment_list_item' key={item.id}>
          <View className='comment_item_wrap'>
            <Image className='comment_item_wrap_avatar' src={item.userInfo.avatarUrl} />
            <Text className='comment_item_wrap_nickname'>{item.userInfo.nickname}</Text>
            <Text className='comment_item_wrap_identity' style={{display: authorId === item.userInfo.id ? '' : 'none'}}>作者</Text>
            <Text className={`iconfont ${item.isLike ? 'icon-xihuanfill' : 'icon-xin'}`}
              onClick={() => toggleLike(item.id, index)}
            />
          </View>
          <View className='comment_item_box'>
            <View className='comment_item_box_content'>{item.content}</View>
            <Text className='comment_item_box_time'>{formatTime(item.createTime)}</Text>
          </View>
        </View>) : <NoResult title='暂无评论' />
      }
    </View>
  </View>
}

export default React.memo(Comment)
